<template>
  <div class="drawer-main">
    <el-drawer
      ref="drawerMain"
      :title="drawerTitle"
      :visible.sync="drawer"
      direction="rtl"
      size="62%"
      :wrapperClosable="false"
      @closed="handleClose"
    >
      <div class="drawer-content">
        <div class="info-main">
          <div class="info-item">
            <span class="info-label">{{ $i18n.t("bomBuyer.materialName") }}：</span>
            <span class="info-text">{{ infoData.materialName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">{{ $i18n.t("bomBuyer.quantity") }}：</span>
            <span class="info-text">{{ infoData.materialNum }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">包装单位：</span>
            <span class="info-text">{{ infoData.demandPackUnit }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">{{ $i18n.t("bomBuyer.offerDeadline") }}：</span>
            <span class="info-text">{{ infoData.deadlineTime }}</span>
          </div>
          <!-- <div class="info-item item-full">
            <span class="info-label">{{ $i18n.t("bomBuyer.picture") }}：</span>
            <div class="img-box">
              <el-image
                v-if="infoData.materialPhotoUrl"
                style="width: 100px; height: 100px"
                :src="infoData.materialPhotoUrl"
                :preview-src-list="[infoData.materialPhotoUrl]"
              >
              </el-image>
            </div>
          </div> -->
        </div>
        <ele-form
          ref="supplementFormRef"
          :disabled="false"
          v-model="supplementForm"
          v-bind="baseFormConfig"
        >
        </ele-form>
        <div class="btns" >
          <el-button @click="drawer = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
        <el-tabs
          ref="tabRef"
          v-model="activeName"
          @tab-click="handleClick"
        >
          <!-- <el-tab-pane
            label="原厂件"
            name="first"
          ></el-tab-pane> -->
          <!-- <el-tab-pane
            label="拆车件"
            name="fourth"
          ></el-tab-pane> -->
          <el-tab-pane
            label="品牌件"
            name="second"
          ></el-tab-pane>
          <el-tab-pane
            label="其他"
            name="third"
          ></el-tab-pane>
        </el-tabs>
        <el-table
          :data="tableData"
          stripe
          border
          height="calc(100vh - 380px)"
          style="width: 100%;"
        >
          <el-table-column
            :label="$t('common.order')"
            type="index"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="supplierName"
            :label="$t('bomBuyer.label1')"
            min-width="140"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template #default="scope">
              <span>
                <span v-if="drawerType==1">
                  {{ scope.row.supplierName.replace(/./g, "*") }}
                </span>
                <span
                  v-if="drawerType==2"
                  class="bule-span"
                  @click="showSupplierViewer(scope.row)"
                >
                  {{ scope.row.supplierName }}
                </span>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="activeName!='first' && activeName!='fourth' && brandList"
            prop="brand"
            :label="$t('bomBuyer.label2')"
            min-width="140"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template #default="scope">
              <span>{{ findBrandName(scope.row.brand) }} </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="unitPrice"
            :label="$t('bomBuyer.label3')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="freight"
            :label="$t('bomBuyer.label4')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="totalPrice"
            :label="$t('bomBuyer.label5')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="isProvide"
            :label="$t('bomBuyer.label9')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
            <template #default="scope">
              <span>{{ scope.row.isProvide===0?'无货':scope.row.isProvide===1?'有货':'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="quoStatusStr"
            :label="$t('bomBuyer.label10')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
            <!-- <template #default="scope">
              <span>{{ scope.row.isWin===0?'未中标':scope.row.isWin===1?'已中标':'已报价' }}</span>
            </template> -->
          </el-table-column>
          <el-table-column
            prop="pictureList"
            label="图片"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
            <template #default="scope">
              <el-link
                type="primary"
                @click="showImgViewer(scope.row.pictureList)"
              >
                {{ scope.row.pictureList.length ? $i18n.t('common.view') : '-'}}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="arrivalDays"
            label="到货天数"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="arrivalTime"
            :label="$t('bomBuyer.label6')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="deliveryMode"
            :label="$t('bomBuyer.label7')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="createTime"
            :label="$t('bomBuyer.label8')"
            :show-overflow-tooltip="true"
            min-width="170"
            align="center"
          >
          </el-table-column>
          
          <el-table-column
            prop="remarks"
            :label="$t('bomBuyer.label11')"
            :show-overflow-tooltip="true"
            min-width="140"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="operate"
            :label="$t('common.operation')"
            :show-overflow-tooltip="true"p
            min-width="200"
            align="center"
          >
            <template #default="scope">
              <!-- :disabled="scope.row.demandStatus !='询价中' &&  scope.row.demandStatus !='待选择'" -->
              <el-button type="primary" plain :disabled="scope.row.quoStatus != 6" @click="confirm(scope.row)">确认</el-button>
              <el-button type="danger" plain :disabled="scope.row.quoStatus != 6" @click="reject(scope.row)">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        title="供应商信息"
        :visible.sync="dialogVisible"
        :append-to-body="true"
        width="400px"
      >
        <div class="supplier-dialog-main">
          <div class="supplier-info-main">
            <div class="info-item">
              <div class="info-label">
                {{ $t('bomBuyer.label12') }}：
              </div>
              <div class="info-text">
                {{ supplierInfo.supplierName||'-' }}
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">
                {{ $t('bomBuyer.label13') }}：
              </div>
              <div class="info-text">
                {{ supplierInfo.contactName||'-' }}
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">
                {{ $t('bomBuyer.label14') }}：
              </div>
              <div class="info-text">
                {{ supplierInfo.contactPhone||'-' }}
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">
                {{ $t('bomBuyer.label15') }}：
              </div>
              <div class="info-text">
                {{ supplierInfo.contactEmail||'-' }}
              </div>
            </div>
          </div>
        </div>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogVisible = false"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="驳回"
        @close="rejectQuit"
        :visible.sync="rejectVisible"
        :append-to-body="true"
        width="600px"
      >
        <div class="supplier-dialog-main">
          <ele-form  ref="validateForm"
            v-model="rejectFormData"
            v-bind="rejectFormDialog"
          >
          </ele-form>
        </div>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="rejectQuit">取 消</el-button>
          <el-button
            type="primary"
            @click="rejectSubmit"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-drawer>
    <el-image-viewer
      v-if="showViewer"
      :zIndex='99999'
      :on-close="closeViewer"
      :url-list="showViewerImages"
      :initialIndex="initialIndex"
    />
  </div>
</template>
<script>
import { getQuoteList, mesPcMaterialDemandUpdate, requirementUpdate } from '@/api/materials/bomBuyer.js'
import url from "@/axios/url";
import store from "@/store";
const { mesUrl, adminUrl } = url();
import { deleteFile } from "@/api/common";
import { formDescDialogMixin } from './detailDrawerConfig'
import {
  mesTmMaterialBrandPage
} from "@/api/materials/brand";
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  mixins: [formDescDialogMixin],
  components: {
    ElImageViewer
  },
  data() {
    return {
      showViewer: false,
      initialIndex: 0,
      showViewerImages: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
      ],
      currentRow: {},
      rejectFormData: {},
      rejectVisible: false,
      drawer: false,
      supplementForm: {
        remarks: null,
        pictureList: null
      },
      baseFormConfig: {
        span: 24,
        disabled: false,
        inline: true,
        isShowSubmitBtn: false,
        isShowBackBtn: false,
        rules: {
          remarks: [
            { max: 150, message: $i18n.t("common.overlongPrompt", { length: 150 }), trigger: ["change", "blur"] }
          ],
        },
        formDesc: {
          remarks: {
            type: "textarea",
            label: $i18n.t("supplier.remarks"),
            layout: 12,
            required: false,
            // disabled: (d) => !!d.id,
          },
          pictureList: {
            type: "image-uploader",
            label: $i18n.t("supplier.uploadImages"),
            layout: 12,
            required: false,
            attrs: {
              // limit: 5,
              fileSize: 3, // 文件大小限制 单位M
              // fileType: ["png"],
              multiple: true, // 是否支持多选
              // disabled: true,
              size: 60, // 图片显示大小
              action: `${adminUrl}file`,
              data: {
                bucket: "messervice",
              },
              headers: {
                Satoken: store.getters.token,
              },
              beforeRemove: (data, list) => {
                const bucket = "messervice";
                const filename = data.title;
                console.log(filename)
                return new Promise((resolve, reject) => {
                  deleteFile(`${adminUrl}file`, {
                    bucket,
                    filename,
                  })
                    .then((res) => {
                      resolve(res.data);
                    })
                    .catch((error) => {
                      reject(error);
                    });
                });
              },
              responseFn(response, file) {
                return {
                  src: response.result.path,
                  ...response.result,
                };
              },
            },
          }
        }
      },
      brandList: null,
      infoData: {
        id: null,
        materialCode: null,
        demandPackUnit: null,
        materialName: null,
        materialNum: null,
        materialPhotoUrl: null,
        deadlineTime: null,
        demandStatus: null
      },
      tableData: [],
      activeName: 'second',
      allData: {
        originalData: [],
        qualityData: [],
        otherData: [],
        dismantlingData: []
      },
      dialogVisible: false,
      supplierInfo: {
        supplierName: null,
        contactName: null,
        contactPhone: null,
        contactEmail: null
      }
    }
  },
  computed: {
    drawerTitle() {
      return $i18n.t('common.details')
    },
    drawerType() {
      if (['询价中', '待选择'].includes(this.infoData.demandStatus)) {
        return 1
      }
      if (['已确认', '部分到货', '已到货', '已领取', '已结算'].includes(this.infoData.demandStatus)) {
        return 2
      }
      if (['未响应'].includes(this.infoData.demandStatus)) {
        return 3
      }
      return 0
    }
  },
  methods: {
    //关闭图片预览弹框
    closeViewer() {
        this.showViewer = false
        this.initialIndex = 0
      },
      //图片预览展示
      showImgViewer(pic = null) {
        this.showViewer = true
        this.showViewerImages = pic ? pic : (this.materialDetail.materialPhotoUrl?.split(',') || [])
        console.log(this.showViewerImages)
      },
    reject(row) {
      this.currentRow = row
      this.rejectVisible = true
      // requirementUpdate()
    },
    confirm(row) {
      this.$confirm('此操作将接受当前报价, 是否继续?', $i18n.t('common.tip'), {
        confirmButtonText: $i18n.t('common.ok'),
        cancelButtonText: $i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        // TODO
        let data = {
            ...row,
            isWin: 1,
          }
          requirementUpdate(data).then(res => {
            if(res.data.code == 0) {
              this.$message.success(this.$t("common.submitSuccess"))
              this.getTableData()
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(err => {
            this.getTableData()
          })
       }).catch(() => {
      })
    },
    validateComponent() {
      let allForm = [this.$refs[`validateForm`]]
      console.log('forms', allForm)
      const validators = allForm.filter(form => form)
        .map((form) => form.validateForm)
        .filter(Boolean);
      console.log('validators', validators)

      return Promise.all(validators.map((fn) => fn()));
    },
    rejectQuit() {
      this.rejectVisible = false
      this.rejectFormData = {}
    },
    rejectSubmit() {
      this.validateComponent().then(res => {
          let data = {
            ...this.currentRow,
            ...this.rejectFormData,
            isPass: 0,
            rejectPictures: this.rejectFormData.rejectPictures?.map(ele => ele.path).join(',') || ''
          }
          requirementUpdate(data).then(res => {
            if(res.data.code == 0) {
              this.$message.success(this.$t("common.submitSuccess"))
              this.getTableData()
            } else {
              this.$message.error(res.data.message)
            }
            this.rejectVisible = false
          }).catch(err => {
            this.getTableData()
            this.rejectVisible = false
          })
        }).catch(err => {
          console.log(err)
        })
    },
    handleSubmit() {
      let pics = []
      let getPic = this.supplementForm.pictureList ? this.supplementForm.pictureList.map(ele => {
        pics.push(ele.path)
      }) : (pics = [])
      mesPcMaterialDemandUpdate({
        ...this.supplementForm,
        id: this.infoData.id,
        materialPhotoUrl: pics.join(',')
      }).then( res =>{
        this.$message.success(this.$t('common.operateSuccess'))
        this.$emit('updateList')
      })
      .catch( err => {
        this.$message.error(err)
      })
      
    },
    handleClick() {
      this.$refs.tabRef.setCurrentName(this.activeName)
      if (this.activeName == 'first') {
        this.tableData = this.allData.originalData
      }
      if (this.activeName == 'second') {
        this.tableData = this.allData.qualityData
      }
      if (this.activeName == 'third') {
        this.tableData = this.allData.otherData
      }
      if (this.activeName == 'fourth') {
        this.tableData = this.allData.dismantlingData
      }
    },
    showSupplierViewer(row) {
      this.dialogVisible = true
      this.supplierInfo.supplierName = row.supplierName
      this.supplierInfo.contactName = row.username
      this.supplierInfo.contactPhone = row.mobile
      this.supplierInfo.contactEmail = row.email
    },
    findBrandName(id) {
      return this.brandList.find(ele => ele.id == id)?.brand || ''
    },
    getBrandList() {
      mesTmMaterialBrandPage({
        pageNum: 1,
        pageSize: 1000000,
        materialCode: this.infoData.materialCode
      }).then(res => {
        if(res.data.code == 0) {
          this.brandList = res.data.result.records
        }
      })
    },
    getTableData() {
      let params = {
        demandId: this.infoData.id
      }
      getQuoteList(params).then(res => {
        if (res.data.success) {
          let data = res.data.result
          data.forEach(ele => {
            if (ele.materialType == 1) {
              this.allData.originalData = ele.quotationList
            }
            if (ele.materialType == 2) {
              this.allData.qualityData = ele.quotationList
            }
            if (ele.materialType == 3) {
              this.allData.otherData = ele.quotationList
            }
            if(ele.materialType == 4) {
              this.allData.dismantlingData = ele.quotationList
            }
          })
          this.activeName = 'second'
          this.tableData = this.allData.qualityData
        }
      })
    },
    clearDialog() {
      this.drawer = false
    },
    handleClose() {
      this.infoData = {
        id: null,
        materialName: null,
        materialNum: null,
        materialPhotoUrl: null,
        deadlineTime: null
      }
      this.tableData = []
      this.allData = {
        originalData: [],
        qualityData: [],
        otherData: [],
        dismantlingData: []
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer-main {
  /deep/.el-drawer__body {
    padding: 0 20px;
  }
  .info-main {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 20px;
    .info-item {
      width: 40%;
      display: flex;
      margin-bottom: 10px;
      font-size: 14px;
      .info-label {
        padding-right: 2px;
      }
    }
    .item-full {
      width: 100%;
    }
  }
  .bule-span {
    color: #3c7fcd;
    cursor: pointer;
  }
}
.supplier-info-main {
  .info-item {
    display: flex;
    margin-bottom: 10px;
  }
  .info-label {
    width: 110px;
    line-height: 24px;
    text-align: right;
  }
}
.btns {
  margin: 20px 0;
  text-align: right;
}
</style>